using org.openERP.erpCommon.utility;
using org.openERP.erpCommon.reference;
using org.openERP.erpCommon.ad_actionButton;
using org.openERP.data.FieldProvider;
using org.openERP.utils.FormatUtilities;
using org.openERP.erpCommon.info.LocationSearchData;
using org.openERP.Base.secureApp.HttpSecureAppServlet;
using org.openERP.Base.secureApp.VariablesSecureApp;
using org.openERP.erpCommon.businessUtility.WindowTabs;
using org.openERP.erpCommon.businessUtility.WindowTabsData;
using org.openERP.utils.Replace;
using org.openERP.xmlEngine.XmlDocument;
using org.openERP.data.UtilSql;

// imports para transacciones
using org.openERP.database.ConnectionProvider;
using java.sql.Connection;

using org.openERP.erpCommon.utility.DateTimeData;

namespace org.openERP.erpWindows.Client
{


    public class Client : HttpSecureAppServlet
    {
        protected static const String windowId = "109";
        protected static const String tabId = "145";
        protected static const String tableLevel = "6";
        protected static const String defaultTabView = "EDIT";
        protected static const double SUBTABS_COL_SIZE = 15;
        protected TableSQLData tableSQL = null;

        public void doPost(HttpServletRequest request, HttpServletResponse response)
        {
            VariablesSecureApp vars = new VariablesSecureApp(request);

            if (!Utility.hasAccess(this, vars, tableLevel, Utility.getContext(this, vars, "#AD_Client_ID", windowId), Utility.getContext(this, vars, "#AD_Org_ID", windowId), windowId, tabId))
            {
                bdError(response, "AccessTableNoView", vars.getLanguage());
                return;
            }

            try
            {
                tableSQL = new TableSQLData(vars, this, tabId, Utility.getContext(this, vars, "#User_Org", windowId), Utility.getContext(this, vars, "#User_Client", windowId));
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }

            String strOrderBy = vars.getSessionValue(tabId + "|orderby");
            if (!strOrderBy.equals(""))
            {
                vars.setSessionValue(tabId + "|newOrder", "1");
            }

            if (vars.commandIn("DEFAULT"))
            {

                String strAD_Client_ID = vars.getGlobalVariable("inpadClientId", windowId + "|AD_Client_ID", "");


                String strView = vars.getSessionValue(tabId + "|Client.view");
                if (strView.equals(""))
                {
                    strView = defaultTabView;

                    if (strView.equals("EDIT"))
                    {
                        if (strAD_Client_ID.equals("")) strAD_Client_ID = firstElement(vars);
                        if (strAD_Client_ID.equals("")) strView = "RELATION";
                    }
                }
                if (strView.equals("EDIT"))

                    printPageEdit(response, request, vars, false, strAD_Client_ID);

                else printPageDataSheet(response, vars, strAD_Client_ID);
            }
            else if (vars.commandIn("DIRECT"))
            {
                String strAD_Client_ID = vars.getStringParameter("inpDirectKey");
                if (strAD_Client_ID.equals("")) strAD_Client_ID = vars.getRequiredGlobalVariable("inpadClientId", windowId + "|AD_Client_ID");
                else vars.setSessionValue(windowId + "|AD_Client_ID", strAD_Client_ID);

                vars.setSessionValue(tabId + "|Client.view", "EDIT");

                printPageEdit(response, request, vars, false, strAD_Client_ID);

            }
            else if (vars.commandIn("TAB"))
            {


                String strView = vars.getSessionValue(tabId + "|Client.view");
                String strAD_Client_ID = "";
                if (strView.equals(""))
                {
                    strView = defaultTabView;
                    if (strView.equals("EDIT"))
                    {
                        strAD_Client_ID = firstElement(vars);
                        if (strAD_Client_ID.equals("")) strView = "RELATION";
                    }
                }
                if (strView.equals("EDIT"))
                {

                    if (strAD_Client_ID.equals("")) strAD_Client_ID = firstElement(vars);
                    printPageEdit(response, request, vars, false, strAD_Client_ID);

                }
                else printPageDataSheet(response, vars, "");
            }
            else if (vars.commandIn("SEARCH"))
            {
                String strParamName = vars.getRequestGlobalVariable("inpParamName", tabId + "|paramName");

                vars.removeSessionValue(windowId + "|AD_Client_ID");
                String strAD_Client_ID = "";

                String strView = vars.getSessionValue(tabId + "|Client.view");
                if (strView.equals("")) strView = defaultTabView;

                if (strView.equals("EDIT"))
                {
                    strAD_Client_ID = firstElement(vars);
                    if (strAD_Client_ID.equals("")) strView = "RELATION";
                }

                if (strView.equals("EDIT"))

                    printPageEdit(response, request, vars, false, strAD_Client_ID);

                else printPageDataSheet(response, vars, strAD_Client_ID);
            }
            else if (vars.commandIn("RELATION"))
            {


                String strAD_Client_ID = vars.getGlobalVariable("inpadClientId", windowId + "|AD_Client_ID", "");
                vars.setSessionValue(tabId + "|Client.view", "RELATION");
                printPageDataSheet(response, vars, strAD_Client_ID);
            }
            else if (vars.commandIn("NEW"))
            {


                printPageEdit(response, request, vars, true, "");

            }
            else if (vars.commandIn("EDIT"))
            {

                String strAD_Client_ID = vars.getGlobalVariable("inpadClientId", windowId + "|AD_Client_ID", "");
                vars.setSessionValue(tabId + "|Client.view", "EDIT");

                setHistoryCommand(request, "EDIT");
                printPageEdit(response, request, vars, false, strAD_Client_ID);

            }
            else if (vars.commandIn("NEXT"))
            {

                String strAD_Client_ID = vars.getRequiredStringParameter("inpadClientId");

                String strNext = nextElement(vars, strAD_Client_ID);

                printPageEdit(response, request, vars, false, strNext);
            }
            else if (vars.commandIn("PREVIOUS"))
            {

                String strAD_Client_ID = vars.getRequiredStringParameter("inpadClientId");

                String strPrevious = previousElement(vars, strAD_Client_ID);

                printPageEdit(response, request, vars, false, strPrevious);
            }
            else if (vars.commandIn("FIRST_RELATION"))
            {

                vars.setSessionValue(tabId + "|Client.initRecordNumber", "0");
                response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
            }
            else if (vars.commandIn("PREVIOUS_RELATION"))
            {

                String strInitRecord = vars.getSessionValue(tabId + "|Client.initRecordNumber");
                String strRecordRange = Utility.getContext(this, vars, "#RecordRange", windowId);
                int intRecordRange = strRecordRange.equals("") ? 0 : Integer.parseInt(strRecordRange);
                if (strInitRecord.equals("") || strInitRecord.equals("0"))
                {
                    vars.setSessionValue(tabId + "|Client.initRecordNumber", "0");
                }
                else
                {
                    int initRecord = (strInitRecord.equals("") ? 0 : Integer.parseInt(strInitRecord));
                    initRecord -= intRecordRange;
                    strInitRecord = ((initRecord < 0) ? "0" : Integer.toString(initRecord));
                    vars.setSessionValue(tabId + "|Client.initRecordNumber", strInitRecord);
                }
                vars.removeSessionValue(windowId + "|AD_Client_ID");

                response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
            }
            else if (vars.commandIn("NEXT_RELATION"))
            {

                String strInitRecord = vars.getSessionValue(tabId + "|Client.initRecordNumber");
                String strRecordRange = Utility.getContext(this, vars, "#RecordRange", windowId);
                int intRecordRange = strRecordRange.equals("") ? 0 : Integer.parseInt(strRecordRange);
                int initRecord = (strInitRecord.equals("") ? 0 : Integer.parseInt(strInitRecord));
                if (initRecord == 0) initRecord = 1;
                initRecord += intRecordRange;
                strInitRecord = ((initRecord < 0) ? "0" : Integer.toString(initRecord));
                vars.setSessionValue(tabId + "|Client.initRecordNumber", strInitRecord);
                vars.removeSessionValue(windowId + "|AD_Client_ID");

                response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
            }
            else if (vars.commandIn("FIRST"))
            {

                String strAD_Client_ID = vars.getRequiredStringParameter("inpadClientId");

                String strFirst = firstElement(vars);

                printPageEdit(response, request, vars, false, strFirst);
            }
            else if (vars.commandIn("LAST_RELATION"))
            {

                String strLast = lastElement(vars);
                printPageDataSheet(response, vars, strLast);
            }
            else if (vars.commandIn("LAST"))
            {

                String strAD_Client_ID = vars.getRequiredStringParameter("inpadClientId");

                String strLast = lastElement(vars);

                printPageEdit(response, request, vars, false, strLast);
            }
            else if (vars.commandIn("SAVE_NEW_RELATION", "SAVE_NEW_NEW", "SAVE_NEW_EDIT"))
            {

                OBError myError = null;
                ClientData data = null;
                int total = 0;
                try
                {
                    data = getEditVariables(vars);
                    String strSequence = SequenceIdData.getSequence(this, "AD_Client", vars.getClient());
                    log4j.info("Sequence: " + strSequence);
                    data.adClientId = strSequence;
                    total = data.insert(this);
                }
                catch (ServletException ex)
                {
                    myError = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                    if (!myError.isConnectionAvailable())
                    {
                        bdErrorConnection(response);
                        return;
                    }
                    else vars.setMessage(tabId, myError);
                }
                if (myError == null && total == 0)
                {
                    myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=DBExecuteError");
                    vars.setMessage(tabId, myError);
                }
                if (myError != null)
                {
                    if (data != null)
                    {
                        data.adClientId = "";
                        vars.setEditionData(tabId, data);
                    }
                    response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
                }
                else
                {
                    if (myError == null)
                    {
                        myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsInserted");
                        myError.setMessage(total + " " + myError.getMessage());
                        vars.setMessage(tabId, myError);
                    }
                    vars.setSessionValue(windowId + "|AD_Client_ID", data.adClientId);
                    if (vars.commandIn("SAVE_NEW_NEW")) response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
                    else if (vars.commandIn("SAVE_NEW_EDIT")) response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
                    else response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
                }
            }
            else if (vars.commandIn("SAVE_EDIT_RELATION", "SAVE_EDIT_NEW", "SAVE_EDIT_EDIT", "SAVE_EDIT_NEXT"))
            {

                String strAD_Client_ID = vars.getRequiredGlobalVariable("inpadClientId", windowId + "|AD_Client_ID");
                int total = 0;
                ClientData data = null;
                OBError myError = null;
                try
                {
                    data = getEditVariables(vars);
                    total = data.update(this);
                }
                catch (ServletException ex)
                {
                    myError = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                    if (!myError.isConnectionAvailable())
                    {
                        bdErrorConnection(response);
                        return;
                    }
                    else vars.setMessage(tabId, myError);
                }
                if (myError == null && total == 0)
                {
                    myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=DBExecuteError");
                    vars.setMessage(tabId, myError);
                }
                if (myError != null)
                {
                    if (data != null)
                    {

                        vars.setEditionData(tabId, data);
                    }
                    response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
                }
                else
                {
                    if (myError == null)
                    {
                        myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsUpdated");
                        myError.setMessage(total + " " + myError.getMessage());
                        vars.setMessage(tabId, myError);
                    }
                    if (vars.commandIn("SAVE_EDIT_NEW")) response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
                    else if (vars.commandIn("SAVE_EDIT_EDIT")) response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
                    else if (vars.commandIn("SAVE_EDIT_NEXT"))
                    {
                        String strNext = nextElement(vars, strAD_Client_ID);
                        vars.setSessionValue(windowId + "|AD_Client_ID", strNext);
                        response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
                    }
                    else response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
                }

            }
            else if (vars.commandIn("DELETE"))
            {

                String strAD_Client_ID = vars.getRequiredStringParameter("inpadClientId");
                //ClientData data = getEditVariables(vars);
                int total = 0;
                OBError myError = null;
                try
                {
                    total = ClientData.delete(this, strAD_Client_ID);
                }
                catch (ServletException ex)
                {
                    myError = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                    if (!myError.isConnectionAvailable())
                    {
                        bdErrorConnection(response);
                        return;
                    }
                    else vars.setMessage(tabId, myError);
                }
                if (myError == null && total == 0)
                {
                    myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=DBExecuteError");
                    vars.setMessage(tabId, myError);
                }
                vars.removeSessionValue(windowId + "|adClientId");
                vars.setSessionValue(tabId + "|Client.view", "RELATION");
                if (myError == null)
                {
                    myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsDeleted");
                    myError.setMessage(total + " " + myError.getMessage());
                    vars.setMessage(tabId, myError);
                }
                response.sendRedirect(strDireccion + request.getServletPath());

            }
            else if (vars.getCommand().toUpperCase().startsWith("BUTTON") || vars.getCommand().toUpperCase().startsWith("SAVE_BUTTON"))
            {
                pageErrorPopUp(response);
            }
            else pageError(response);
        }

        ClientData getEditVariables(VariablesSecureApp vars)
        {
            ClientData data = new ClientData();
            data.adOrgId = vars.getRequiredGlobalVariable("inpadOrgId", windowId + "|AD_Org_ID"); data.adClientId = vars.getRequestGlobalVariable("inpadClientId", windowId + "|AD_Client_ID"); data.value = vars.getStringParameter("inpvalue"); data.name = vars.getRequiredStringParameter("inpname"); data.description = vars.getStringParameter("inpdescription"); data.isactive = vars.getStringParameter("inpisactive", "N"); data.adLanguage = vars.getStringParameter("inpadLanguage"); data.adLanguager = vars.getStringParameter("inpadLanguage_R"); data.ismultilingualdocument = vars.getStringParameter("inpismultilingualdocument", "N"); data.smtphost = vars.getStringParameter("inpsmtphost"); data.issmtpauthorization = vars.getStringParameter("inpissmtpauthorization", "N"); data.requestemail = vars.getStringParameter("inprequestemail"); data.requestfolder = vars.getStringParameter("inprequestfolder"); data.requestuser = vars.getStringParameter("inprequestuser"); data.requestuserpw = vars.getStringParameter("inprequestuserpw"); data.weborderemail = vars.getStringParameter("inpweborderemail"); data.webdir = vars.getStringParameter("inpwebdir"); data.webinfo = vars.getStringParameter("inpwebinfo"); data.webparam1 = vars.getStringParameter("inpwebparam1"); data.webparam2 = vars.getStringParameter("inpwebparam2"); data.webparam3 = vars.getStringParameter("inpwebparam3"); data.webparam4 = vars.getStringParameter("inpwebparam4"); data.webparam5 = vars.getStringParameter("inpwebparam5"); data.webparam6 = vars.getStringParameter("inpwebparam6"); data.documentdir = vars.getStringParameter("inpdocumentdir");
            data.createdby = vars.getUser();
            data.updatedby = vars.getUser();
            if (data.value.equals("")) data.value = Utility.getDocumentNo(this, vars.getClient(), "AD_Client", true);

            return data;
        }

        ClientData[] getRelationData(ClientData[] data)
        {
            if (data != null)
            {
                for (int i = 0; i < data.length; i++) { data[i].adOrgId = FormatUtilities.truncate(data[i].adOrgId, 14); data[i].adClientId = FormatUtilities.truncate(data[i].adClientId, 14); data[i].value = FormatUtilities.truncate(data[i].value, 20); data[i].name = FormatUtilities.truncate(data[i].name, 50); data[i].description = FormatUtilities.truncate(data[i].description, 50); data[i].adLanguage = FormatUtilities.truncate(data[i].adLanguage, 14); data[i].smtphost = FormatUtilities.truncate(data[i].smtphost, 20); data[i].requestemail = FormatUtilities.truncate(data[i].requestemail, 20); data[i].requestfolder = FormatUtilities.truncate(data[i].requestfolder, 20); data[i].requestuser = FormatUtilities.truncate(data[i].requestuser, 20); data[i].requestuserpw = FormatUtilities.truncate(data[i].requestuserpw, 20); data[i].weborderemail = FormatUtilities.truncate(data[i].weborderemail, 20); data[i].webdir = FormatUtilities.truncate(data[i].webdir, 20); data[i].webinfo = FormatUtilities.truncate(data[i].webinfo, 50); data[i].webparam1 = FormatUtilities.truncate(data[i].webparam1, 20); data[i].webparam2 = FormatUtilities.truncate(data[i].webparam2, 20); data[i].webparam3 = FormatUtilities.truncate(data[i].webparam3, 20); data[i].webparam4 = FormatUtilities.truncate(data[i].webparam4, 20); data[i].webparam5 = FormatUtilities.truncate(data[i].webparam5, 20); data[i].webparam6 = FormatUtilities.truncate(data[i].webparam6, 20); data[i].documentdir = FormatUtilities.truncate(data[i].documentdir, 20); }
            }
            return data;
        }



        void refreshSessionEdit(VariablesSecureApp vars, FieldProvider[] data)
        {
            if (data == null || data.length == 0) return;
            vars.setSessionValue(windowId + "|AD_Client_ID", data[0].getField("adClientId")); vars.setSessionValue(windowId + "|AD_Org_ID", data[0].getField("adOrgId"));
        }

        void refreshSessionNew(VariablesSecureApp vars)
        {
            ClientData[] data = ClientData.selectEdit(this, vars.getLanguage(), vars.getStringParameter("inpadClientId", ""));
            if (data == null || data.length == 0) return;
            refreshSessionEdit(vars, data);
        }

        String nextElement(VariablesSecureApp vars, String strSelected)
        {
            if (strSelected == null || strSelected.equals("")) return firstElement(vars);
            if (tableSQL != null)
            {
                FieldProvider[] data = null;
                try
                {
                    String strSQL = ModelSQLGeneration.generateSQL(this, vars, tableSQL, (tableSQL.getTableName() + "." + tableSQL.getKeyColumn() + " AS ID"), new Vector<String>(), new Vector<String>());
                    ExecuteQuery execquery = new ExecuteQuery(this, strSQL, tableSQL.getParameterValues());
                    data = execquery.select(0, 0);
                }
                catch (Exception e)
                {
                    if (log4j.isDebugEnabled()) log4j.debug("Error getting next element");
                    e.printStackTrace();
                }
                if (data != null)
                {
                    boolean found = false;
                    for (int i = 0; i < data.length; i++)
                    {
                        if (!found && data[i].getField("ID").equals(strSelected)) found = true;
                        else if (found) return data[i].getField("ID");
                    }
                }
            }
            return strSelected;
        }

        int getKeyPosition(VariablesSecureApp vars, String strSelected)
        {
            if (log4j.isDebugEnabled()) log4j.debug("getKeyPosition: " + strSelected);
            if (tableSQL != null)
            {
                FieldProvider[] data = null;
                try
                {
                    String strSQL = ModelSQLGeneration.generateSQL(this, vars, tableSQL, (tableSQL.getTableName() + "." + tableSQL.getKeyColumn() + " AS ID"), new Vector<String>(), new Vector<String>());
                    ExecuteQuery execquery = new ExecuteQuery(this, strSQL, tableSQL.getParameterValues());
                    data = execquery.select(0, 0);
                }
                catch (Exception e)
                {
                    if (log4j.isDebugEnabled()) log4j.debug("Error getting key position");
                    e.printStackTrace();
                }
                if (data != null)
                {
                    for (int i = 0; i < data.length; i++)
                    {
                        if (log4j.isDebugEnabled()) log4j.debug("row: " + i + " - key: " + data[i].getField("ID"));
                        if (data[i].getField("ID").equals(strSelected)) return i;
                    }
                }
            }
            return 0;
        }

        String previousElement(VariablesSecureApp vars, String strSelected)
        {
            if (strSelected == null || strSelected.equals("")) return firstElement(vars);
            if (tableSQL != null)
            {
                FieldProvider[] data = null;
                try
                {
                    String strSQL = ModelSQLGeneration.generateSQL(this, vars, tableSQL, (tableSQL.getTableName() + "." + tableSQL.getKeyColumn() + " AS ID"), new Vector<String>(), new Vector<String>());
                    ExecuteQuery execquery = new ExecuteQuery(this, strSQL, tableSQL.getParameterValues());
                    data = execquery.select(0, 0);
                }
                catch (Exception e)
                {
                    if (log4j.isDebugEnabled()) log4j.debug("Error getting previous element");
                    e.printStackTrace();
                }
                if (data != null)
                {
                    String previous = strSelected;
                    for (int i = 0; i < data.length; i++)
                    {
                        if (data[i].getField("ID").equals(strSelected)) return previous;
                        previous = data[i].getField("ID");
                    }
                }
            }
            return strSelected;
        }

        String firstElement(VariablesSecureApp vars)
        {
            if (tableSQL != null)
            {
                FieldProvider[] data = null;
                try
                {
                    String strSQL = ModelSQLGeneration.generateSQL(this, vars, tableSQL, (tableSQL.getTableName() + "." + tableSQL.getKeyColumn() + " AS ID"), new Vector<String>(), new Vector<String>());
                    ExecuteQuery execquery = new ExecuteQuery(this, strSQL, tableSQL.getParameterValues());
                    data = execquery.select(0, 1);
                }
                catch (Exception e)
                {
                    if (log4j.isDebugEnabled()) log4j.debug("Error getting first element");
                    e.printStackTrace();
                }
                if (data != null && data.length != 0) return data[0].getField("ID");
            }
            return "";
        }

        String lastElement(VariablesSecureApp vars)
        {
            if (tableSQL != null)
            {
                FieldProvider[] data = null;
                try
                {
                    String strSQL = ModelSQLGeneration.generateSQL(this, vars, tableSQL, (tableSQL.getTableName() + "." + tableSQL.getKeyColumn() + " AS ID"), new Vector<String>(), new Vector<String>());
                    ExecuteQuery execquery = new ExecuteQuery(this, strSQL, tableSQL.getParameterValues());
                    data = execquery.select(0, 0);
                }
                catch (Exception e)
                {
                    if (log4j.isDebugEnabled()) log4j.debug("Error getting last element");
                    e.printStackTrace();
                }
                if (data != null && data.length != 0) return data[data.length - 1].getField("ID");
            }
            return "";
        }

        void printPageDataSheet(HttpServletResponse response, VariablesSecureApp vars, String strAD_Client_ID)
        {
            if (log4j.isDebugEnabled()) log4j.debug("Output: dataSheet");

            String strParamName = vars.getSessionValue(tabId + "|paramName");

            boolean hasSearchCondition = false;
            vars.removeEditionData(tabId);
            if (!(strParamName.equals(""))) hasSearchCondition = true;
            String strOffset = vars.getSessionValue(tabId + "|offset");
            String selectedRow = "0";
            if (!strAD_Client_ID.equals(""))
            {
                selectedRow = Integer.toString(getKeyPosition(vars, strAD_Client_ID));
            }

            String[] discard ={ "isNotFiltered", "isNotTest" };
            if (hasSearchCondition) discard[0] = new String("isFiltered");
            if (vars.getSessionValue("#ShowTest", "N").equals("Y")) discard[1] = new String("isTest");
            XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openERP/erpWindows/Client/Client_Relation", discard).createXmlDocument();

            ToolBar toolbar = new ToolBar(this, vars.getLanguage(), "Client", false, "document.frmMain.inpadClientId", "grid", "..", "".equals("Y"), "Client", strReplaceWith, false);
            toolbar.prepareRelationTemplate("N".equals("Y"), hasSearchCondition, vars.getSessionValue("#ShowTest", "N").equals("Y"), "N".equals("Y"));
            xmlDocument.setParameter("toolbar", toolbar.toString());

            String strOrderBy = vars.getSessionValue(tabId + "|orderby");
            StringBuffer orderByArray = new StringBuffer();
            if (!strOrderBy.equals(""))
            {
                vars.setSessionValue(tabId + "|newOrder", "1");
                String positions = vars.getSessionValue(tabId + "|orderbyPositions");
                orderByArray.append("var orderByPositions = new Array(\n");
                if (!positions.equals(""))
                {
                    StringTokenizer tokens = new StringTokenizer(positions, ",");
                    boolean firstOrder = true;
                    while (tokens.hasMoreTokens())
                    {
                        if (!firstOrder) orderByArray.append(",\n");
                        orderByArray.append("\"").append(tokens.nextToken()).append("\"");
                        firstOrder = false;
                    }
                }
                orderByArray.append(");\n");
                String directions = vars.getSessionValue(tabId + "|orderbyDirections");
                orderByArray.append("var orderByDirections = new Array(\n");
                if (!positions.equals(""))
                {
                    StringTokenizer tokens = new StringTokenizer(directions, ",");
                    boolean firstOrder = true;
                    while (tokens.hasMoreTokens())
                    {
                        if (!firstOrder) orderByArray.append(",\n");
                        orderByArray.append("\"").append(tokens.nextToken()).append("\"");
                        firstOrder = false;
                    }
                }
                orderByArray.append(");\n");
            }

            xmlDocument.setParameter("selectedColumn", "\nvar selectedRow = " + selectedRow + ";\n" + orderByArray.toString());
            xmlDocument.setParameter("direction", "var baseDirection = \"" + strReplaceWith + "/\";\n");
            xmlDocument.setParameter("windowId", windowId);
            xmlDocument.setParameter("KeyName", "adClientId");
            xmlDocument.setParameter("language", "LNG_POR_DEFECTO=\"" + vars.getLanguage() + "\";");
            xmlDocument.setParameter("theme", vars.getTheme());
            //xmlDocument.setParameter("buttonReference", Utility.messageBD(this, "Reference", vars.getLanguage()));
            try
            {
                WindowTabs tabs = new WindowTabs(this, vars, tabId, windowId);
                xmlDocument.setParameter("parentTabContainer", tabs.parentTabs());
                xmlDocument.setParameter("mainTabContainer", tabs.mainTabs());
                xmlDocument.setParameter("childTabContainer", tabs.childTabs());
                NavigationBar nav = new NavigationBar(this, vars.getLanguage(), "Client_Relation.html", "Client", "W", strReplaceWith, tabs.breadcrumb());
                xmlDocument.setParameter("navigationBar", nav.toString());
                LeftTabsBar lBar = new LeftTabsBar(this, vars.getLanguage(), "Client_Relation.html", strReplaceWith);
                xmlDocument.setParameter("leftTabs", lBar.relationTemplate());
            }
            catch (Exception ex)
            {
                throw new ServletException(ex);
            }
            try
            {
                KeyMap key = new KeyMap(this, vars, tabId, windowId);
                xmlDocument.setParameter("keyMap", key.getRelationKeyMaps());
            }
            catch (Exception ex)
            {
                throw new ServletException(ex);
            }
            {
                OBError myMessage = vars.getMessage(tabId);
                vars.removeMessage(tabId);
                if (myMessage != null)
                {
                    xmlDocument.setParameter("messageType", myMessage.getType());
                    xmlDocument.setParameter("messageTitle", myMessage.getTitle());
                    xmlDocument.setParameter("messageMessage", myMessage.getMessage());
                }
            }


            xmlDocument.setParameter("grid", Utility.getContext(this, vars, "#RecordRange", windowId));

            response.setContentType("text/html; charset=UTF-8");
            PrintWriter out1 = response.getWriter();
            out1.println(xmlDocument.print());
            out1.close();
        }

        void printPageEdit(HttpServletResponse response, HttpServletRequest request, VariablesSecureApp vars, boolean boolNew, String strAD_Client_ID)
        {
            if (log4j.isDebugEnabled()) log4j.debug("Output: edit");
            String strOrderByFilter = vars.getSessionValue(tabId + "|orderby");
            String orderClause = " AD_Client.Name";
            if (strOrderByFilter == null || strOrderByFilter.equals("")) strOrderByFilter = orderClause;
            String strCommand = null;
            ClientData[] data = null;
            XmlDocument xmlDocument = null;
            FieldProvider dataField = vars.getEditionData(tabId);
            vars.removeEditionData(tabId);
            String strParamName = vars.getSessionValue(tabId + "|paramName");



            boolean hasSearchCondition = false;
            if (!(strParamName.equals(""))) hasSearchCondition = true;

            String strParamSessionDate = vars.getGlobalVariable("inpParamSessionDate", Utility.getTransactionalDate(this, vars, windowId), "");
            String strParamUser = vars.getUser();
            String buscador = "";
            String[] discard = { "", "isNotTest" };

            if (vars.getSessionValue("#ShowTest", "N").equals("Y")) discard[1] = new String("isTest");
            if (dataField == null)
            {
                if (!boolNew)
                {
                    discard[0] = new String("newDiscard");
                    data = ClientData.selectEdit(this, vars.getLanguage(), strAD_Client_ID);

                    refreshSessionEdit(vars, data);
                    strCommand = "EDIT";
                }

                if (boolNew || data == null || data.length == 0)
                {
                    discard[0] = new String("editDiscard");
                    strCommand = "NEW";
                    data = new ClientData[0];
                }
                else
                {
                    discard[0] = new String("newDiscard");
                }
            }
            else
            {
                if (dataField.getField("adClientId").equals(""))
                {
                    discard[0] = new String("editDiscard");
                    strCommand = "NEW";
                    boolNew = true;
                }
                else
                {
                    discard[0] = new String("newDiscard");
                    strCommand = "EDIT";
                }
            }
            xmlDocument = xmlEngine.readXmlTemplate("org/openERP/erpWindows/Client/Client_Edition", discard).createXmlDocument();

            ToolBar toolbar = new ToolBar(this, vars.getLanguage(), "Client", (boolNew || (dataField == null && (data == null || data.length == 0))), "document.frmMain.inpadClientId", "", "..", "".equals("Y"), "Client", strReplaceWith, true);
            toolbar.prepareEditionTemplate("N".equals("Y"), hasSearchCondition, vars.getSessionValue("#ShowTest", "N").equals("Y"), "N".equals("Y"));
            xmlDocument.setParameter("toolbar", toolbar.toString());

            try
            {
                WindowTabs tabs = new WindowTabs(this, vars, tabId, windowId);
                xmlDocument.setParameter("parentTabContainer", tabs.parentTabs());
                xmlDocument.setParameter("mainTabContainer", tabs.mainTabs());
                xmlDocument.setParameter("childTabContainer", tabs.childTabs());
                NavigationBar nav = new NavigationBar(this, vars.getLanguage(), "Client_Relation.html", "Client", "W", strReplaceWith, tabs.breadcrumb());
                xmlDocument.setParameter("navigationBar", nav.toString());
                LeftTabsBar lBar = new LeftTabsBar(this, vars.getLanguage(), "Client_Relation.html", strReplaceWith);
                xmlDocument.setParameter("leftTabs", lBar.editionTemplate());
            }
            catch (Exception ex)
            {
                throw new ServletException(ex);
            }
            try
            {
                KeyMap key = new KeyMap(this, vars, tabId, windowId);
                xmlDocument.setParameter("keyMap", key.getEditionKeyMaps(boolNew));
            }
            catch (Exception ex)
            {
                throw new ServletException(ex);
            }



            if (dataField == null)
            {
                if (boolNew || data == null || data.length == 0)
                {
                    refreshSessionNew(vars);
                    data = ClientData.set("0", Utility.getDefault(this, vars, "AD_Client_ID", "@AD_CLIENT_ID@", "109", ""), Utility.getDefault(this, vars, "Value", "", "109", ""), Utility.getDefault(this, vars, "Name", "", "109", ""), Utility.getDefault(this, vars, "Description", "", "109", ""), "Y", Utility.getDefault(this, vars, "AD_Language", "", "109", ""), Utility.getDefault(this, vars, "IsMultiLingualDocument", "", "109", "N"), Utility.getDefault(this, vars, "SMTPHost", "", "109", ""), Utility.getDefault(this, vars, "IsSmtpAuthorization", "N", "109", "N"), Utility.getDefault(this, vars, "RequestEMail", "", "109", ""), Utility.getDefault(this, vars, "RequestFolder", "", "109", ""), Utility.getDefault(this, vars, "RequestUser", "", "109", ""), Utility.getDefault(this, vars, "RequestUserPW", "", "109", ""), Utility.getDefault(this, vars, "WebOrderEMail", "", "109", ""), Utility.getDefault(this, vars, "WebDir", "", "109", ""), Utility.getDefault(this, vars, "WebInfo", "", "109", ""), Utility.getDefault(this, vars, "WebParam1", "", "109", ""), Utility.getDefault(this, vars, "WebParam2", "", "109", ""), Utility.getDefault(this, vars, "WebParam3", "", "109", ""), Utility.getDefault(this, vars, "WebParam4", "", "109", ""), Utility.getDefault(this, vars, "WebParam5", "", "109", ""), Utility.getDefault(this, vars, "WebParam6", "", "109", ""), Utility.getDefault(this, vars, "DocumentDir", "", "109", ""));

                }
            }



            xmlDocument.setParameter("commandType", strCommand);
            xmlDocument.setParameter("buscador", buscador);
            xmlDocument.setParameter("windowId", windowId);
            xmlDocument.setParameter("changed", (strCommand.equals("NEW") ? "1" : ""));
            xmlDocument.setParameter("language", "LNG_POR_DEFECTO=\"" + vars.getLanguage() + "\";");
            xmlDocument.setParameter("theme", vars.getTheme());

            xmlDocument.setParameter("paramSessionDate", strParamSessionDate);

            xmlDocument.setParameter("direction", "var baseDirection = \"" + strReplaceWith + "/\";\n");
            {
                OBError myMessage = vars.getMessage(tabId);
                vars.removeMessage(tabId);
                if (myMessage != null)
                {
                    xmlDocument.setParameter("messageType", myMessage.getType());
                    xmlDocument.setParameter("messageTitle", myMessage.getTitle());
                    xmlDocument.setParameter("messageMessage", myMessage.getMessage());
                }
            }


            if (dataField == null) xmlDocument.setData("structure1", data);
            else
            {
                FieldProvider[] dataAux = new FieldProvider[1];
                dataAux[0] = dataField;
                xmlDocument.setData("structure1", dataAux);
            }
            try
            {
                ComboTableData comboTableData = null;
                comboTableData = new ComboTableData(vars, this, "18", "AD_Language", "106", "", Utility.getContext(this, vars, "#User_Org", windowId), Utility.getContext(this, vars, "#User_Client", windowId), 0);
                Utility.fillSQLParameters(this, vars, (dataField == null ? data[0] : dataField), comboTableData, windowId, (dataField == null ? data[0].getField("adLanguage") : dataField.getField("adLanguage")));
                xmlDocument.setData("reportAD_Language", "liststructure", comboTableData.select(!strCommand.equals("NEW")));
                comboTableData = null;

            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                throw new ServletException(ex);
            }
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter out1 = response.getWriter();
            out1.println(xmlDocument.print());
            out1.close();
        }


        public String getServletInfo()
        {
            return "Servlet Client. This Servlet was made by Wad constructor";
        } // fin del método getServletInfo()
    }
}